package henu.service;


import henu.dao.factory.DaoFactory;
import henu.bean.Questions;
import henu.bean.Student;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.T;
import org.apache.struts2.ServletActionContext;

/**
 * 数据的导入
 * @author wuhaifeng
 */
public class ImportExcel {
	public static void main(String[] args) {
		ImportExcel ie = new ImportExcel();
		//ie.questionts("C:/Users/Administrator/Downloads/allexam.xls");
	}
	/**
	 * 导入题库
	 * @param 题目文件所在的路径
	 * */
	public static int questionts(String filepath) {
		int count = 0;
		InputStream is = null;
		HSSFWorkbook hssfWorkbook = null;
		try {
			is = new FileInputStream(filepath);
			hssfWorkbook = new HSSFWorkbook(is);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{			
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
			HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
			if (hssfSheet == null) {
				continue;
			}
			for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {

				HSSFRow hssfRow = hssfSheet.getRow(rowNum);
				if (hssfRow == null) {
					continue;
				}
				Questions ques = new Questions();
				ques.setContent(getValue(hssfRow.getCell(0))); // 
				ques.setAnswer(getValue(hssfRow.getCell(1)));
				ques.setSubject(getValue(hssfRow.getCell(2))); //科目
				ques.setType(getValue(hssfRow.getCell(3)));
				ques.setOptiona(getValue(hssfRow.getCell(4)));
				ques.setOptionb(getValue(hssfRow.getCell(5)));
				ques.setOptionc(getValue(hssfRow.getCell(6)));
				ques.setOptiond(getValue(hssfRow.getCell(7)));
				ques.setRemark((getValue(hssfRow.getCell(8))));
				int result = DaoFactory.getQuesttionDaoInstance().save(ques);
				if (result > 0) {
					count++;
				}
			}
		}
		return count;
	}
	/**
	 * 把excel中的数据类型转化为java的数据类型
	 * */
	private static String getValue(HSSFCell hssfCell) {
		if (hssfCell == null)
			return "NULL";
		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			// 返回数值类型的值
			NumberFormat df = new DecimalFormat("#0");
			return df.format(hssfCell.getNumericCellValue());
		} else {
			// 返回字符串类型的值
			return String.valueOf(hssfCell.getStringCellValue());
		}
	}

}
